import * as React from 'react'
import TwsReactMarkdownPreview from '../../common/markdown/MarkdownPreview'
import { Input, Button, Form, message, Tag, Divider, Icon } from 'antd/es';
import { FormComponentProps } from 'antd/es/form';
declare var vscode:any
const FAILED_STATUS = -1
const SUCCESS_STATUS = 1

interface AnswerSubmitBoxProps extends FormComponentProps {
    id: number
    submitSimpleCodingQuizAnswer: Function
    setLoading: Function
    submission: any
    getHomeworkQuizzes: Function
    getRunningLogs: Function
    task: any
    loading: boolean
    userAnswerRepo: string
    branch: string
    quiz: any
    reviewQuiz: any
    getAssignment: Function
}
class AnswerSubmitBox extends React.Component<AnswerSubmitBoxProps, any>{

    componentDidMount = () => {
        const { id} = this.props
        this.props.getAssignment(id, () => {
            const {quiz} = this.props
            this.props.form.setFieldsValue({
                userAnswerRepo: quiz.userAnswer,
                branch: quiz.answerBranch,
            })
        })
    }

    componentWillReceiveProps = (nextProps: any) => {
        const { quiz } = nextProps
        if (quiz.id === this.props.quiz.id) {
            return false
        }
        this.props.form.setFieldsValue({
            userAnswerRepo: quiz.userAnswer,
            branch: quiz.answerBranch,
        })
        return true
    }

    submit = (e:any) => {
        e.preventDefault();
        this.props.form.validateFields((err: any, values: any) => {
            if (!err) {
                const { userAnswerRepo, branch } = values
                const defaultBranch = branch || 'master'
                const data = this.buildSubmitData(userAnswerRepo, defaultBranch)
                this.props.submitSimpleCodingQuizAnswer(data, () => {
                    message.success('答案提交成功')
                    if (this.needRunScript()) {
                        this.props.setLoading(true)
                        this.loadLogs()
                    }
                })
            }
        })
    }

    needRunScript = () => {
        const { quiz } = this.props
        return !!quiz.evaluateScript
    }

    loadLogs = () => {
        const { submission, quiz } = this.props
        const { userId } = vscode.getState()
        const { assignmentId, id } = quiz
        
        if (submission.status === FAILED_STATUS) {
            message.warning('编译不通过')
            this.props.setLoading(false)
            return
        }
        if (submission.status === SUCCESS_STATUS) {
            message.success('编译通过')
            this.props.getHomeworkQuizzes(assignmentId)
            this.props.setLoading(false)
            return
        }
        this.props.getRunningLogs(userId, assignmentId, id)
        window.setTimeout(() => this.loadLogs(), 1500)
    }

    getRunningResult = () => {
        const { submission = {} } = this.props
        const result = submission.status
            ? <Tag color={submission.status === SUCCESS_STATUS ? '#87d068' : 'red'}>
                {submission.status === SUCCESS_STATUS ? '通过' : '失败'}
            </Tag>
            : <Tag color='gold'><Icon type='sync' spin />进行中</Tag>

        return (<div className={submission.id ? '' : 'hidden'}>
            <Divider />
            <p>{result}</p>
            <div className='result-content'>
                {submission.jobMessage}
            </div>
        </div>)
    }

    buildSubmitData = (userAnswerRepo: string, branch: string) => {
        const { quiz, task } = this.props
        const { userId } = vscode.getState()
        return {
            assignmentId: quiz.assignmentId,
            quizId: quiz.id,
            taskId: task.id,
            userAnswerRepo,
            branch,
            studentId: userId
        }
    }

    render() {
        const { loading, quiz, reviewQuiz } = this.props
        const { getFieldDecorator } = this.props.form
        return <div>
            <TwsReactMarkdownPreview source={'编程题模板库地址' + '：' + quiz.templateRepository} />
            <div style={{ background: 'white', margin: '-7px 0px 0px 0px' }}>
                <Form style={{ width: 500 }} onSubmit={this.submit}>
                    <Form.Item>
                        {getFieldDecorator('userAnswerRepo', {
                            rules: [{
                                pattern: new RegExp('^((http|https)://)*?(www.)*?(git).*?$'),
                                message: '请输入正确的git仓库地址',
                            }],
                        })(
                            <Input addonBefore={'git仓库地址'}
                            />
                        )}
                    </Form.Item>
                    <Form.Item>
                        {getFieldDecorator('branch', {
                        })(
                            <Input addonBefore={'git仓库分支'} placeholder={'默认master'} />,
                        )}
                    </Form.Item>
                    <Form.Item>
                        <Button htmlType='submit' style={{ width: 250 }} loading={loading}>
                            {reviewQuiz.id ? '再次提交代码' : '提交代码地址'}
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            {this.needRunScript() ? this.getRunningResult() : ''}
        </div>
    }
}

export default Form.create<AnswerSubmitBoxProps>({})(AnswerSubmitBox)